package ui.user;

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
import ui.admin.student.*;
import hibernate.dao.CourseDAO;
import hibernate.dao.StudentDAO;
import hibernate.entity.Accounts;
import hibernate.entity.Courses;
import hibernate.entity.Students;
import java.io.IOException;
import java.io.InputStream;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.RequestScoped;
import javax.faces.context.FacesContext;
import javax.servlet.http.HttpSession;
import org.primefaces.event.FileUploadEvent;
import org.primefaces.event.TransferEvent;
import org.primefaces.model.DualListModel;
import org.primefaces.model.UploadedFile;
import ui.admin.AbstractAdminBean;
import ui.admin.course.CourseManager;
import ui.common.AbstractUIBean;
import util.Converter;
import util.FileUpload;
import util.Md5Generator;
import util.RandomGenerator;

//import util.UploadBean;
/**
 * c
 *
 * @author QuynhDu
 */
@ManagedBean
@RequestScoped
public class UserStudentManager extends AbstractAdminBean {

    StudentDAO sDAO = new StudentDAO();
    private Accounts currAcc = new Accounts();
    private String username;
    private String password;
    private String email;
    private String fullname;
    private String address;
    private String strBirthday;
    Date birthday = new Date();
    private String studentimage;
    private boolean gender;
//    UploadBean uploadBean = new UploadBean();
    List<Courses> sourceCourse,
            targetCourse;
    DualListModel<Courses> dualCourse = new DualListModel<Courses>();
    CourseDAO cDao = new CourseDAO();

    public UserStudentManager() {
       
        sourceCourse = new ArrayList<Courses>();
        targetCourse = new ArrayList<Courses>();
    }

    public String getStrBirthday() {
        return strBirthday;
    }

    public void setStrBirthday(String strBirthday) {
        this.strBirthday = strBirthday;
    }

    public List<Courses> getAvaiCourse() {
        return sourceCourse;
    }

    public void setAvaiCourse(List<Courses> avaiCourse) {
        this.sourceCourse = avaiCourse;
    }

    /**
     * @return the currAcc
     */
    public Accounts getCurrAcc() {
        return currAcc;
    }

    /**
     * @param currAcc the currAcc to set
     */
    public void setCurrAcc(Accounts currAcc) {
        this.currAcc = currAcc;
    }

    /**
     * @return the username
     */
    public String getUsername() {
        return username;
    }

    /**
     * @param username the username to set
     */
    public void setUsername(String username) {
        this.username = username;
    }

    public void setBirthday(Date birthday) {
        this.birthday = birthday;
    }

    /**
     * @return the password
     */
    public String getPassword() {
        return password;
    }

    /**
     * @param password the password to set
     */
    public void setPassword(String password) {
        this.password = password;
    }

    /**
     * @return the email
     */
    public String getEmail() {
        return email;
    }

    /**
     * @param email the email to set
     */
    public void setEmail(String email) {
        this.email = email;
    }

//    public UploadBean getUploadBean() {
//        return uploadBean;
//    }
//
//    public void setUploadBean(UploadBean uploadBean) {
//        this.uploadBean = uploadBean;
//    }
    /**
     * @return the fullname
     */
    public String getFullname() {
        return fullname;
    }

    /**
     * @param fullname the fullname to set
     */
    public void setFullname(String fullname) {
        this.fullname = fullname;
    }

    /**
     * @return the address
     */
    public String getAddress() {
        return address;
    }

    /**
     * @param address the address to set
     */
    public void setAddress(String address) {
        this.address = address;
    }

    /**
     * @return the studentimage
     */
    public String getStudentimage() {
        return studentimage;
    }

    /**
     * @param studentimage the studentimage to set
     */
    public void setStudentimage(String studentimage) {
        this.studentimage = studentimage;
    }

    public DualListModel<Courses> getDualCourse() {
        return dualCourse;
    }

    public void setDualCourse(DualListModel<Courses> dualCourse) {
        this.dualCourse = dualCourse;
    }

    public boolean isGender() {
        return gender;
    }

    public void setGender(boolean gender) {
        this.gender = gender;
    }

    /**
     * @param Students a student's fields to modify
     * @return String
     * @see edit page
     */
    public String edit(Students stu) {
        currAcc = stu.getAccounts();
        username = currAcc.getUserName();
        password = currAcc.getPassword();
        address = currAcc.getAddress();
        fullname = currAcc.getFullName();
        email = currAcc.getEmail();
        strBirthday = Converter.dateJavaToString(currAcc.getBirthday());
        studentimage = stu.getStudentImage();
        HttpSession session = (HttpSession) FacesContext.getCurrentInstance().getExternalContext().getSession(true);
        session.setAttribute("editStudent", stu);
        return "edit";
    }

    /**
     * @param Accounts an account for set birthday in it
     * @param str represent for a string of birthday
     * @return void
     */
    void addBirthday(Accounts acc, String str) {
        try {
            acc.setBirthday(Converter.stringToDateJava(strBirthday));
        } catch (ParseException ex) {
            Logger.getLogger(CourseManager.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    /**
     * @return String
     * @see list page with extra student that is modified successfully
     */
    public String doupdate() {
        HttpSession session = getHttpSession();
        Students stu = (Students) session.getAttribute("editStudent");
        currAcc.setUserName(username);
        try {
            currAcc.setBirthday(Converter.stringToDateJava(strBirthday));
        } catch (ParseException ex) {
            Logger.getLogger(StudentManager.class.getName()).log(Level.SEVERE, null, ex);
        }
        currAcc.setAddress(address);
        currAcc.setFullName(fullname);
        currAcc.setEmail(email);
        addBirthday(currAcc, strBirthday);
        if (session.getAttribute("studentimage") != null) {
            studentimage = String.valueOf(session.getAttribute("studentimage"));
        }
        stu.setStudentImage(studentimage);
        try {
            hbTransaction = hbSession.beginTransaction();
            currAcc = (Accounts) hbSession.merge(currAcc);
            hbSession.update(currAcc);
            stu.setAccounts(currAcc);
            stu = (Students) hbSession.merge(stu);
            hbSession.update(stu);
            hbTransaction.commit();
            showPrimeMessage("Success", "Student " + stu.getStudentId() + " updated");
            return "list?faces-redirect=true";
        } catch (Exception e) {
            hbTransaction.rollback();
            showPrimeMessage("Error", "Unexpected error! update fail");
        }

        return null;
    }

    /**
     * @return String
     * @see list page with added student
     */
    public String docreate() {
        try {
            hbTransaction = hbSession.beginTransaction();
            currAcc = new Accounts(username, email, fullname, address, "a", birthday, gender);
            currAcc.setStatus(0);
            HttpSession sesion = getHttpSession();
            studentimage = String.valueOf(sesion.getAttribute("studentimage"));
            String p = RandomGenerator.randomString();
            p = "staff";

            String hash = Md5Generator.getMd5(p);

            currAcc.setPassword(hash);
            currAcc.setRoleId(3);
            hbSession.save(currAcc);
            Students stu = new Students(currAcc, studentimage);
            HttpSession session = getHttpSession();

            if (session.getAttribute("studentimage") != null) {
                studentimage = String.valueOf(session.getAttribute("studentimage"));
                stu.setStudentImage(studentimage);
            }
            stu.setStudentImage("empty");
            stu.setStatus(0);
            hbSession.save(stu);
            hbTransaction.commit();
            return "list?faces-redirect=true";
        } catch (Exception e) {
            hbTransaction.rollback();
        }
        return null;
    }

    /**
     * @param Students a student for pick into some course
     * @return String
     * @see pickcourse page
     */
    public String pickCourse(Students s) {
        sourceCourse = new CourseDAO().readAll();
        targetCourse = Converter.iteratorToList(s.getCourseses().iterator());
        dualCourse = new DualListModel<Courses>(sourceCourse, targetCourse);
        HttpSession session = (HttpSession) FacesContext.getCurrentInstance().getExternalContext().getSession(true);
        session.setAttribute("editStudent", s);
        return "pickcourse";
    }

    /**
     * @param TransferEvent an event for transferring the course
     * @return void
     */
    public void courseTransfer(TransferEvent event) {
        HttpSession session = (HttpSession) FacesContext.getCurrentInstance().getExternalContext().getSession(true);
        targetCourse = (List<Courses>) session.getAttribute("courses");
        if (targetCourse == null) {
            targetCourse = new ArrayList<Courses>();
        }
        for (Object item : event.getItems()) {
            int id = Integer.parseInt(item.toString());
            Courses c = cDao.readByID(id);
            targetCourse.add(c);
            showPrimeMessage("Result", String.valueOf(targetCourse.size()));
        }
        session.setAttribute("courses", targetCourse);
    }

    /**
     * @return String
     * @see list page of student
     */
    public String updateCourses() {
        HttpSession session = (HttpSession) FacesContext.getCurrentInstance().getExternalContext().getSession(true);
        targetCourse = (List<Courses>) session.getAttribute("courses");
        Students stu = (Students) session.getAttribute("editStudent");
        hbTransaction = hbSession.beginTransaction();
        try {
            for (Courses courses : targetCourse) {
                courses.getStudentses().add(stu);
                courses = (Courses) hbSession.merge(courses);
                hbSession.save(courses);
            }
            hbTransaction.commit();
            return "student-list";
        } catch (Exception e) {
            hbTransaction.rollback();
        }
        showPrimeMessage("Success", "Updated");
        return null;
    }

    /**
     * @param Students a student for removing
     * @return void
     * @see list page in which deleted student does not exist
     */
    public void remove(Students stu) {

        if (sDAO.remove(stu) > 0) {
            showPrimeMessage("Success", "Course " + stu.getStudentId() + " has been removed");
        }
    }

    /**
     * @return List<Students>
     * @see a whole list of student is studying in the University
     */
    public List<Students> getAllStudent() {
        return new StudentDAO().readLiving();
    }

    /**
     * @param FileUploadEvent an event to carry out upload any file
     * @return void
     */
    public void upload(FileUploadEvent event) {
        try {
            InputStream is = null;
            UploadedFile uploadFile = event.getFile();
            is = event.getFile().getInputstream();
            studentimage = new FileUpload().processFile(uploadFile);
            System.out.println("Done!");
            FacesMessage msg = new FacesMessage("Succesful", event.getFile().getFileName() + " is uploaded.");
            FacesContext.getCurrentInstance().addMessage(null, msg);
            HttpSession session = getHttpSession();
            session.setAttribute("studentimage", studentimage);
        } catch (IOException ex) {
            Logger.getLogger(StudentManager.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    /**
     * @param Students a student chosen to view his details
     * @return String
     * @see studentdetail page
     */
    public String viewDetail(Students s) {
        HttpSession session = getHttpSession();
        session.setAttribute("viewStudent", s);
        return "admin-student-detail";
    }
}
